package com.zf.common.redis.utils;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.api.sync.RedisCommands;

import java.util.concurrent.ExecutionException;

/**
 * 使用 lettuce 作为连接redis的客户端
 */
public class LettuceRedisClientUtils {

    /**
     * 创建客户端
     */
    public static RedisClient getRedisClient() {
        RedisURI redisURI = RedisURI.builder()
                .withHost("localhost")
                .withPort(6379)
                .withPassword("123456".toCharArray())
                .withDatabase(0)
                .build();
        return RedisClient.create(redisURI);
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        testSync();
        testAsync();
    }

    /**
     * 测试同步操作
     */
    public static void testSync() {
        // 创建redis客户端
        RedisClient redisClient = getRedisClient();

        // 开启一个redis连接
        StatefulRedisConnection<String, String> connect = redisClient.connect();

        // 从连接中获取一个 同步执行的 命令API；不会创建新的连接，还是在当前连接中执行命令
        RedisCommands<String, String> sync = connect.sync();

        // 同步执行redis命令
        String a = sync.set("a", "22");
        Long a1 = sync.incrby("a", 3);
        Long a2 = sync.incr("a");

        System.out.println(a); // "OK"
        System.out.println(a1);
        System.out.println(a2);

        connect.close();
    }

    /**
     * 测试同步操作
     */
    public static void testAsync() throws ExecutionException, InterruptedException {
        // 创建redis客户端
        RedisClient redisClient = getRedisClient();

        // 开启一个redis连接
        StatefulRedisConnection<String, String> connect = redisClient.connect();

        // 从连接中获取一个 异步执行的 命令API；不会创建新的连接，还是在当前连接中执行命令
        RedisAsyncCommands<String, String> async = connect.async();

        // 异步执行redis命令
        RedisFuture<String> a = async.set("a", "22");
        RedisFuture<Long> a1 = async.incrby("a", 3);
        RedisFuture<Long> a2 = async.incr("a");

        System.out.println(a.get()); // "OK"
        System.out.println(a1.get());
        System.out.println(a2.get());

        connect.close();
    }
}
